const express = require('express');
const MongoClient = require('mongodb').MongoClient;

const dbUrl = 'mongodb://localhost:27017/practice';

module.exports = function(){
    const router = express.Router();
    router.post('/todoList/findAll', (req, res) => {
        MongoClient.connect(dbUrl, function (err, client) {
            if (err){
                res.status(500).send('db connect failed!');
                client.close()
                return;
            }
    
            var db = client.db('practice')
    
            db.collection('todos').find({"deleted":{$ne:true}}).toArray(function (err, result) {
                if (err){
                    res.status(500).send('db query failed!');
                    client.close();
                    return;
                }
                const data = result.map(({_id, ...rest}) => ({id:_id, ...rest}));
                res.send({success:true,data});
                client.close();
            })
        })
    })
    router.post('/todoList/deleteItem', express.json(), (req, res)=>{
        MongoClient.connect(dbUrl, async function (err, client) {
            if (err){
                res.status(500).send('db connect failed!');
                client.close();
                return;
            }
    
            var db = client.db('practice')
    
            try {
                const { id } = req.body;
                if(!id){
                    res.status(400).send('请求参数错误')
                    client.close();
                    return;
                }
                db.collection('todos').updateOne({'_id': id},{$set:{'deleted':true}},(err,result)=>{//修改
                    res.send(true);
                    client.close();
                })
            } catch (error) {
                console.log(error);
                res.status(500).send('db delete failed!');
                client.close();
            }
        })
    })

    // 单个创建待办事项
    // router.post('/todoList/createItem',express.json(),()=>{
        
    // })

    // 单个更新待办事项
    // router.post('/todoList/updateItem',express.json(),()=>{
        
    // })

    return router;
}